//
//  CRMContinueFollowUpVC.m
//  New_Runway
//
//  Created by NewLife on 2018/3/1.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CRMContinueFollowUpVC.h"
#import "NRWCarRemarkTextView.h"
#import "NRWCarInputItemView.h"
#import "NRWCarChooseTableVC.h"
#import "PickDateView.h"

@interface CRMContinueFollowUpVC ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, PickerDateViewDelegate>

@end

@implementation CRMContinueFollowUpVC
{
    UITableView *tableView;
    
    NRWCarInputItemView *customerLevelItem;
    NRWCarInputItemView *timeItem;
    NRWCarInputItemView *comeItem;
    NRWCarRemarkTextView *remarkTextView;
    
    NSString *_customerLevelId;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBarView.titleLabel.text = @"继续跟进";
    
    [self setupUI];
    
    [self setupRightBtn];
}

- (void)setupUI {
    
    UITableViewController *tvc = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
    [self addChildViewController:tvc];
    tvc.view.frame = CGRectMake(0, self.navH, Screen_width, Screen_height - self.navH - self.BotH);
    tableView = tvc.tableView;
    
    tableView.setSeparatorStyle(UITableViewCellSeparatorStyleNone);
    tableView.delegate = self;
    tableView.dataSource = self;
    
    self.view.addSubview(tableView);
}

- (void)setupRightBtn {
    
    [self.navigationBarView setupRightItemTitle:@"确定"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *identifier = [NSString stringWithFormat:@"%zd",indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:0 reuseIdentifier:identifier];
    }
    
    if (cell.contentView.subviews.count > 0) {
        return cell;
    }
    
    if (indexPath.row == 0) {
        
        customerLevelItem = [[NRWCarInputItemView alloc] initWithInputItemWithPlaceHolder:@"请选择客户级别" delegate:self showArrow:YES];
        customerLevelItem.titleString = @"客户级别";
        customerLevelItem.tag = 0;
        customerLevelItem.frame = CGRectMake(0, 0, Screen_width, 40);
        cell.contentView.addSubview(customerLevelItem);
    } else if (indexPath.row == 1) {
        
        timeItem = [[NRWCarInputItemView alloc] initWithInputItemWithPlaceHolder:@"请选择下次跟进时间" delegate:self showArrow:YES];
        timeItem.titleAttributedString = [@"*下次跟进" attributedStringWithFirstTextColor:getColorFromString(@"ff0000") firstRange:NSMakeRange(0, 1) secondTextColor:getColorFromString(@"323232") secondRange:NSMakeRange(1, @"*下次跟进".length - 1)];
        timeItem.titleRectOffset = -[@"*" sizeWithFont:kPingFangRegular13() andMaxSize:CGSizeMake(100, 100)].width;
        timeItem.tag = 1;
        timeItem.frame = CGRectMake(0, 0, Screen_width, 40);
        cell.contentView.addSubview(timeItem);
    } else if (indexPath.row == 2) {
        
        comeItem = [[NRWCarInputItemView alloc] initWithTwoChooseItemWithTitle1:@"是" title2:@"否"];
        comeItem.titleString = @"是否到店";
        comeItem.chooseIndex = 0;
        comeItem.frame = CGRectMake(0, 0, Screen_width, 40);
        cell.contentView.addSubview(comeItem);
    } else if (indexPath.row == 3) {
        
        UILabel *remarkLabel = DPLabel()
        .setFont(kPingFangRegular13())
        .setTextColor(getColorFromString(@"323232"))
        .setText(@"备注");
        
        remarkTextView = [[NRWCarRemarkTextView alloc] initWithRemarkTextView];
        cell.contentView.addSubview(remarkLabel).addSubview(remarkTextView);
        
        [remarkLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.contentView.mas_top).offset(12.5);
            make.left.equalTo(cell.contentView.mas_left).offset(15.5);
        }];
        
        [remarkTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(remarkLabel.mas_bottom).offset(11);
            make.left.equalTo(cell.contentView.mas_left).offset(16);
            make.right.equalTo(cell.contentView.mas_right).offset(-16);
            make.height.equalTo(@140);
        }];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 3) {
        return 185;
    }
    
    return 40;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
    if (textField.superview == customerLevelItem) {
        
        NRWCarChooseTableVC *vc = [[NRWCarChooseTableVC alloc] init];
        vc.chooseType = NRWCarChooseTableVCTypeLevel;
        [self.navigationController pushViewController:vc animated:YES];
        
        vc.chooseCompleted = ^(NSString *itemId, NSString *itemName) {
            textField.text = itemName;
            _customerLevelId = itemId;
        };
        return NO;
    }
    
    if (textField.superview == timeItem) {
        
        NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        // 获取当前日期
        NSDate* dt = [NSDate date];
        // 指定获取指定年、月、日、时、分、秒的信息
        unsigned unitFlags = NSCalendarUnitYear |
        NSCalendarUnitMonth |  NSCalendarUnitDay |
        NSCalendarUnitHour |  NSCalendarUnitMinute |
        NSCalendarUnitSecond | NSCalendarUnitWeekday;
        // 获取不同时间字段的信息
        NSDateComponents* comp = [gregorian components: unitFlags fromDate:dt];
        
        PickDateView *pick = [[PickDateView alloc] init];
        [pick setDefaultTSelectYear:comp.year defaultSelectMonth:comp.month defaultSelectDay:comp.day];
        pick.delegate = self;
        pick.isShowDay = YES;
        pick.pickerViewHeight = 300;
        [pick show];
        return NO;
    }
    return YES;
}

- (void)pickerDateView:(BasePickView *)pickerDateView selectYear:(NSInteger)year selectMonth:(NSInteger)month selectDay:(NSInteger)day {
    
    timeItem.inputText = [NSString stringWithFormat:@"%zd-%zd-%zd", year, month, day];
}

- (void)rightItemClick {
    
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    
    if (!isEmptyOrNilString(_customerLevelId)) {
        [dictM setObject:_customerLevelId forKey:@"customerLevel"];
    }
    if (!isEmptyOrNilString(customerLevelItem.inputText)) {
        [dictM setObject:customerLevelItem.inputText forKey:@"customerLevelTxt"];
    }
    if (!isEmptyOrNilString(timeItem.inputText)) {
        [dictM setObject:timeItem.inputText forKey:@"nextFollowTime"];
    } else {
        [ShowMessage showHintMessage:@"跟进时间不能为空" duration:1 withRemindId:remindWarning];
        return;
    }
    if (!isEmptyOrNilString(remarkTextView.text)) {
        [dictM setObject:remarkTextView.text forKey:@"followRemark"];
    }
    if (!isEmptyOrNilString(self.customerShopId)) {
        [dictM setObject:self.customerShopId forKey:@"customerShopId"];
    }
    if (!isEmptyOrNilString([NRWCarUser sharedUser].userId)) {
        [dictM setObject:[NRWCarUser sharedUser].userId forKey:@"followerId"];
    }
    if (!isEmptyOrNilString([NRWCarUser sharedUser].userId)) {
        [dictM setObject:[NRWCarUser sharedUser].userName forKey:@"followName"];
    }
    
    [dictM setObject:comeItem.chooseIndex == 0? @"1": @"0" forKey:@"isReach"];
    [dictM setObject:@10 forKey:@"followState"];
    [dictM setObject:@"继续跟进" forKey:@"followResult"];
    
    [SVProgressHUD show];
    [YQNetworking postWithUrl:[NSString stringWithFormat:@"%@%@",CRMContextApi, followAPI] refreshRequest:NO cache:NO params:dictM.copy progressBlock:nil successBlock:^(id response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] integerValue] == 1) {
            kSelfWeak;
            [ShowMessage showHintMessage:@"保存成功" duration:1 withRemindId:remindWarning animationCompleted:^{
                [weakSelf.navigationController safePopViewControllerWithClassName:@"CRMCustomerDetailVC"];
            }];
        } else {
            [SVProgressHUD showErrorWithStatus:response[@"msg"] dismissDelay:1];
        }
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
        [SVProgressHUD dismiss];
    }];
}

@end
